package com.zym.init.core.auth;

import com.alibaba.fastjson2.JSONObject;
import com.zym.init.core.domain.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

/**
 * 拒绝访问处理器
 * 当用户试图访问他们没有权限访问的资源时，这个处理器会被调用
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 处理拒绝访问
     *
     * @param request               that resulted in an <code>AccessDeniedException</code>
     * @param response              so that the user agent can be advised of the failure
     * @param accessDeniedException that caused the invocation
     * @throws IOException      in the event of an IOException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        AjaxResult result = AjaxResult.permission();
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}
